﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;

namespace RegisterTool
{
    public class ClientSysInfo
    {
        /// <summary>
        /// 获取本地IP
        /// </summary>
        /// <returns></returns>
        public static string Get_UserIP()
        {
            string ip = "";
            string name = Dns.GetHostName();
            IPAddress[] ipadrlist = Dns.GetHostAddresses(name);
            foreach (IPAddress ipa in ipadrlist)
            {
                if (ipa.AddressFamily == AddressFamily.InterNetwork)
                    ip = ipa.ToString();
                if (ip.StartsWith("10."))
                {
                    return ip;
                }
            }
            return ip;
        }

        /// <summary>
        /// 获取本地IP
        /// </summary>
        /// <returns></returns>
        public static string Get_UserIPs()
        {
            string ip = "";
            string strHostName = Dns.GetHostName(); //得到本机的主机名
            IPHostEntry ipEntry = Dns.GetHostEntry(strHostName); //取得本机IP
            for (int i = 0; i < ipEntry.AddressList.Length; i++)
            {
                ip += "\r\n" + ipEntry.AddressList[i].ToString();
            }
            return ip;
        }



        /// <summary>
        /// 获取本地IP
        /// </summary>
        /// <returns></returns>
        public static IPAddress[] Get_UserIPArray()
        {
            string ip = "";
            string strHostName = Dns.GetHostName(); //得到本机的主机名
            IPHostEntry ipEntry = Dns.GetHostEntry(strHostName); //取得本机IP

            return ipEntry.AddressList;
        }


        /// <summary>
        /// 获取本地IP
        /// </summary>
        /// <returns></returns>
        public static List<string> Get_UserIPList()
        {
            List<string> list = new List<string>();
            string name = Dns.GetHostName();
            IPAddress[] ipadrlist = Dns.GetHostAddresses(name);
            foreach (IPAddress ipa in ipadrlist)
            {
                if (ipa.AddressFamily == AddressFamily.InterNetwork)
                    list.Add(ipa.ToString());
            }
            return list;
        }

        /// <summary>
        /// 获取主机域名
        /// </summary>
        /// <returns></returns>
        public static string Get_HostName()
        {
            return Dns.GetHostName();
        }
        /// <summary>
        /// 获取CPU编号
        /// </summary>
        /// <returns>返回一个字符串类型</returns>
        public static string GetCPUID()
        {
            try
            {
                ManagementClass mc = new ManagementClass("Win32_Processor");
                ManagementObjectCollection moc = mc.GetInstances();
                string strCpuID = null;
                foreach (ManagementObject mo in moc)
                {
                    strCpuID = mo.Properties["ProcessorId"].Value.ToString();
                    break;
                }
                return strCpuID;
            }
            catch
            {
                return "";
            }
        }
        /// <summary>
        /// 获取第一分区硬盘编号
        /// </summary>
        /// <returns>返回一个字符串类型</returns>
        public static string GetHardDiskID()
        {
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
                string strHardDiskID = null;
                foreach (ManagementObject mo in searcher.Get())
                {
                    strHardDiskID = mo["SerialNumber"].ToString().Trim();
                    break;
                }
                if (string.IsNullOrEmpty(strHardDiskID))
                {
                    strHardDiskID = GetHardDiskID_01();
                }
                if (string.IsNullOrEmpty(strHardDiskID))
                {

                    strHardDiskID = GetHardDiskID_02();
                }

                return strHardDiskID;
            }
            catch
            {
                return "";
            }
        }


        //第一種方式获取硬盘ID
        private static string GetHardDiskID_01()
        {
            string DiskID = "";
            try
            {
                String HDid = "";
                ManagementClass mc = new ManagementClass("Win32_PhysicalMedia");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    HDid = (string)mo.Properties["SerialNumber"].Value;
                    if (HDid != string.Empty && HDid != null)
                    {
                        break;
                    }
                }
                moc = null;
                mc = null;
                DiskID = HDid;
            }
            catch
            {
                DiskID = "";
            }
            return DiskID;
        }

        //第二種方式获取硬盘ID
        private static string GetHardDiskID_02()
        {
            string DiskID = "";
            try
            {

                String HDidi = string.Empty;
                ManagementClass cimobject1 = new ManagementClass("Win32_DiskDrive");
                ManagementObjectCollection moc1 = cimobject1.GetInstances();
                foreach (ManagementObject mo in moc1)
                {
                    HDidi = (string)mo.Properties["SerialNumber"].Value;
                    if (HDidi != string.Empty && HDidi != null)
                    {
                        break;
                    }
                }
                cimobject1 = null;
                moc1 = null;
                DiskID = HDidi;
            }
            catch
            {
                DiskID = "";
            }
            return DiskID;
        }

        /// <summary>取第一块硬盘编号</summary>
        private static String GetHardDiskID_03()
        {
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
                String strHardDiskID = null;
                foreach (ManagementObject mo in searcher.Get())
                {
                    strHardDiskID = mo["SerialNumber"].ToString().Trim();
                    break;
                }
                return strHardDiskID;
            }
            catch
            {
                return "";
            }
        }//end


        /// <summary>
        /// 获取网卡的MAC地址
        /// </summary>
        /// <returns>返回一个string</returns>
        public static string GetNetCardMAC()
        {
            try
            {
                string stringMAC = "";
                ManagementClass MC = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection MOC = MC.GetInstances();
                foreach (ManagementObject MO in MOC)
                {
                    if ((bool)MO["IPEnabled"] == true)
                    {
                        stringMAC += ";" + MO["MACAddress"].ToString();
                    }
                }

                return stringMAC.Substring(1).Trim();
            }
            catch
            {
                return "";
            }
        }
        /// <summary>
        /// 获取当前网卡IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetNetCardIP()
        {
            try
            {
                string stringIP = "";
                ManagementClass MC = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection MOC = MC.GetInstances();
                foreach (ManagementObject MO in MOC)
                {
                    if ((bool)MO["IPEnabled"] == true)
                    {
                        string[] IPAddresses = (string[])MO["IPAddress"];
                        if (IPAddresses.Length > 0)
                        {
                            stringIP = IPAddresses[0].ToString();
                            if (stringIP == "0.0.0.0" && IPAddresses.Length > 1)
                            {
                                stringIP = IPAddresses[1].ToString();
                            }
                        }
                    }
                }
                return stringIP;
            }
            catch
            {
                return "";
            }
        }

        public static string QueryComputerSystem(string type)
        {
            string str = null;
            ManagementObjectSearcher objCS = new ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem");
            foreach (ManagementObject objMgmt in objCS.Get())
            {
                str = objMgmt[type].ToString();
            }
            return str;
        }

        public static string Ping(string domainname)
        {

            Ping ping = new Ping();

            string ret = string.Empty;
            try
            {
                System.Diagnostics.Stopwatch ts = new System.Diagnostics.Stopwatch();
                ts.Start();

                PingReply pingReply = ping.Send(domainname);
                //pingReply.Status= IPStatus.Success
                DateTime now;
                string[] array = new string[11];
                array[0] = "Time:\t";
                string[] arg_D4_0 = array;
                int arg_D4_1 = 1;
                now = DateTime.Now;
                arg_D4_0[arg_D4_1] = now.ToString("yyyy-MM-dd HH:mm:ss");
                array[2] = "\nIP:\t";
                array[3] = domainname;
                array[4] = "\n状态:\t";
                array[5] = pingReply.Status.ToString();
                array[6] = "\n时间:\t";
                array[7] = pingReply.RoundtripTime.ToString();
                ts.Stop();
                array[8] = "\n时间:\t";
                array[9] = string.Format("{0}ms", ts.Elapsed.TotalMilliseconds.ToString());
                array[10] = "\n";
                ret = string.Concat(array);
            }
            catch (Exception ex)
            {
                ret = string.Format("{0}\n", ex.Message);
            }

            return ret;
        }


        static Microsoft.VisualBasic.Devices.Computer myInfo = new Microsoft.VisualBasic.Devices.Computer();
        public static void GetMemoryStatus(out float totalGb, out float usedGb)
        {
            //MEMORY_INFO MemInfo;
            //MemInfo = new MEMORY_INFO();
            //GlobalMemoryStatus(ref MemInfo);

            //totalMb = Convert.ToInt64(MemInfo.dwTotalPhys.ToString()) / 1024 / 1024;
            //avaliableMb = Convert.ToInt64(MemInfo.dwAvailPhys.ToString()) / 1024 / 1024;

            //Console.WriteLine("物理内存共有" + totalMb + " MB");
            //Console.WriteLine("可使用的物理内存有" + avaliableMb + " MB");
            totalGb = Convert.ToSingle(myInfo.Info.TotalPhysicalMemory) / 1024 / 1024 / 1024;
            usedGb = Convert.ToSingle(myInfo.Info.TotalPhysicalMemory - myInfo.Info.AvailablePhysicalMemory) / 1024 / 1024 / 1024;
        }


        //#region CPU占用率
        //static PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
        //static PerformanceCounter ramCounter = new PerformanceCounter("Memory", "Available MBytes");



        //  /// <summary>
        // /// 获取CPU占用率
        //  /// </summary>
        //  public static float CpuLoad
        //  {
        //      get
        //      {

        //          return cpuCounter.NextValue();
        //      }
        //  }

        ///// <summary>
        ///// 获取CPU占用率
        ///// </summary>
        //public static float RamLoad
        //{
        //    get
        //    { 
        //        return ramCounter.NextValue();
        //    }
        //}
        //#endregion



        [DllImport("Iphlpapi.dll")]
        private static extern int SendARP(Int32 dest, Int32 host, ref Int32 mac, ref Int32 length);

        [DllImport("Ws2_32.dll")]
        private static extern Int32 inet_addr(string ip);

        /// <summary>
        /// 根据本地IP地址获取MAC地址（Windows API函数方式）
        /// </summary>
        /// <param name="IP"></param>
        /// <returns></returns>
        public static string GetMACFromIP(string IP)
        {
            string strRet = "Unknown";

            string strIPPattern = @"^\d+\.\d+\.\d+\.\d+$";

            Regex objRex = new Regex(strIPPattern);

            if (objRex.IsMatch(IP) == true)
            {
                Int32 intDest = inet_addr(IP);
                Int32[] arrMAC = new Int32[2];
                Int32 intLen = 6;

                int intResult = SendARP(intDest, 0, ref arrMAC[0], ref intLen);

                if (intResult == 0)
                {
                    Byte[] arrbyte = new Byte[8];
                    arrbyte[5] = (Byte)(arrMAC[1] >> 8);
                    arrbyte[4] = (Byte)arrMAC[1];
                    arrbyte[3] = (Byte)(arrMAC[0] >> 24);
                    arrbyte[2] = (Byte)(arrMAC[0] >> 16);
                    arrbyte[1] = (Byte)(arrMAC[0] >> 8);
                    arrbyte[0] = (Byte)arrMAC[0];

                    StringBuilder strbMAC = new StringBuilder();

                    for (int intIndex = 0; intIndex < 6; intIndex++)
                    {
                        if (intIndex > 0) strbMAC.Append("-");
                        strbMAC.Append(arrbyte[intIndex].ToString("X2"));
                    }
                    strRet = strbMAC.ToString();
                }
            }

            return strRet;
        }
    }
}
